package com.mobilepay.moneypig.model.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseFragment;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.activity.mine.AddCardActivity;
import com.mobilepay.moneypig.model.activity.mine.AddCreditActivity;
import com.mobilepay.moneypig.model.activity.mine.BankCardActivity;
import com.mobilepay.moneypig.model.activity.mine.CreditCardActivity;
import com.mobilepay.moneypig.model.activity.mine.IdentifyActivity;
import com.mobilepay.moneypig.model.activity.mine.InComeActivity;
import com.mobilepay.moneypig.model.activity.mine.MineQRCodeActivity;
import com.mobilepay.moneypig.model.activity.mine.MineSetupActivity;
import com.mobilepay.moneypig.model.activity.mine.MineTeamActivity;
import com.mobilepay.moneypig.model.activity.mine.OrderActivity;
import com.mobilepay.moneypig.model.activity.mine.UserInfoActivity;
import com.mobilepay.moneypig.model.activity.mine.VipActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.model.events.UpdateDataEvent;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.CreditListData;
import com.mobilepay.moneypig.response.mine.UserDetailData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.view.WebViewActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by xlm on 2017/7/14 0014
 */

public class PersonFragment extends BaseFragment {
    private static String TAG = "PersonFragment";
    private RelativeLayout mRelativeDetail, mRelativeBook, mCardDetail, mInComeDetail, mRelativeVipGrade, mRelativeTeam, mRelativeQrCode, mRelativeSetup;
    private TextView mTextRealName;
    private TextView mTextHuiyuan;
    private TextView mTextMobile;
    private SmartRefreshLayout smartRefreshLayout;
    private RelativeLayout mRelativeCredit, mRelativeOrder;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_person);
    }

    @Override
    protected void initViews() {
        mTextRealName = (TextView) mLayoutView.findViewById(R.id.me_realname);
        mTextHuiyuan = (TextView) mLayoutView.findViewById(R.id.txt_huiyuan);
        smartRefreshLayout = (SmartRefreshLayout) mLayoutView.findViewById(R.id.person_refresh);
        smartRefreshLayout.setEnableLoadmore(false);

        mRelativeDetail = (RelativeLayout) mLayoutView.findViewById(R.id.detail_persion);
        mCardDetail = (RelativeLayout) mLayoutView.findViewById(R.id.detail_card);
        mInComeDetail = (RelativeLayout) mLayoutView.findViewById(R.id.detail_income);
        mRelativeCredit = (RelativeLayout) mLayoutView.findViewById(R.id.credit_card);
        mRelativeOrder = (RelativeLayout) mLayoutView.findViewById(R.id.order);
        mRelativeBook = (RelativeLayout) mLayoutView.findViewById(R.id.book);

        mRelativeVipGrade = (RelativeLayout) mLayoutView.findViewById(R.id.vip_grade);
        mRelativeTeam = (RelativeLayout) mLayoutView.findViewById(R.id.mine_team);
        mRelativeQrCode = (RelativeLayout) mLayoutView.findViewById(R.id.qr_code);
        mRelativeSetup = (RelativeLayout) mLayoutView.findViewById(R.id.setup);
        mTextMobile = (TextView) mLayoutView.findViewById(R.id.me_mobile);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(getThis());
        getUserDetail();//账户信息
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(UpdateDataEvent event) {

    }

    @Override
    public void onResume() {
        super.onResume();
        getUserDetail();
    }

    @Override
    protected void onSetListener() {
        mRelativeDetail.setOnClickListener(this);
        mInComeDetail.setOnClickListener(this);
        mCardDetail.setOnClickListener(this);
        mRelativeCredit.setOnClickListener(this);
        mRelativeOrder.setOnClickListener(this);
        mRelativeBook.setOnClickListener(this);

        mRelativeVipGrade.setOnClickListener(this);
        mRelativeTeam.setOnClickListener(this);
        mRelativeQrCode.setOnClickListener(this);
        mRelativeSetup.setOnClickListener(this);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getUserDetail();//账户信息
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.detail_persion:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.detail_income:
                startActivity(InComeActivity.class);
                break;
            case R.id.detail_card:
                checkIdentify();
                break;
            case R.id.order:
                startActivity(OrderActivity.class);
                break;
            case R.id.credit_card:
                checkCredit();
                break;
            case R.id.vip_grade:
                startActivity(VipActivity.class);
                break;
            case R.id.mine_team:
                startActivity(MineTeamActivity.class);
                break;
            case R.id.qr_code:
                startActivity(MineQRCodeActivity.class);
                break;
            case R.id.setup:
                startActivity(MineSetupActivity.class);
                break;
            case R.id.book://新手攻略
                Intent intent = new Intent();
                intent.setClass(getActivity(), WebViewActivity.class);
                intent.putExtra(Key.TITLE, "新手攻略");
                intent.putExtra(Key.URL, NetConfig.USER_BOOK);
                startActivity(intent);
                break;
        }
    }

    int authStatus = -1;
    int bankStaus = -1;
    String creditStaus;

    boolean hasCredit = false;

    //检查银行卡状态
    private void checkIdentify() {
        authStatus = App.getApp().getUserDetailInfo().getData().getReal_auth_status();
        bankStaus = App.getApp().getUserDetailInfo().getData().getBank_auth_status();

        if (-1 == authStatus) {
            return;
        }
        switch (authStatus) {
            case 0:
//                showTipDialog();
//                break;
                showTipDialog();
                break;
            case 1:
//                showConfirmDialog("认证信息审核中，请耐心等待");
//                showTipDialog();
                showToastShort("认证审核中");
                break;
            case 2:
//                if (0 == bankStaus) {
//                    showCardDialog();//添加银行卡
//                } else if (1 == bankStaus) {
//                    startActivity(BankCardActivity.class);
//                }
//                if (bankStaus == 0) {
//                    showCardConfirm("请先绑定结算卡");
//                } else {
//                    startActivity(BankCardActivity.class);
//                }

                startActivity(BankCardActivity.class);
                break;
        }
    }

    //检查信用卡认证状态
    private void checkCredit() {
        authStatus = App.getApp().getUserDetailInfo().getData().getReal_auth_status();
        bankStaus = App.getApp().getUserDetailInfo().getData().getBank_auth_status();
        creditStaus = App.getApp().getUserDetailInfo().getData().getIsset_credit();
        if (-1 == authStatus) {
            return;
        }
        switch (authStatus) {
            case 0:
//                showTipDialog();
//                break;
                showTipDialog();
                break;
            case 1:
//                showConfirm("请先通过实名认证");
                showToastShort("认证审核中");
                break;
            case 2:
//                if ("0".equals(creditStaus)) {
////                    showCardDialog();//添加银行卡
//                    showCreditConfirm("请先绑定信用卡");
//                } else {
////                    startActivity(CreditCardActivity.class);
////                    if (hasCredit) {
////                        startActivity(CreditCardActivity.class);
////                    } else {
////                        showCreditDialog();
////                    }
//                    startActivity(CreditCardActivity.class);
//                }
                startActivity(CreditCardActivity.class);
                break;
        }
    }

    private TipDialog confirmCardDialog;

    private void showCardConfirm(String txt) {
        if (confirmCardDialog == null) {
            confirmCardDialog = new TipDialog(getActivity());
        }
        confirmCardDialog.setContent(txt);
        confirmCardDialog.setCancelable(true);
        confirmCardDialog.setConfirm("去绑定");
        confirmCardDialog.show();
        confirmCardDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmCardDialog.dismiss();
                startActivity(AddCardActivity.class);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmCardDialog.dismiss();
            }
        });
    }

    private TipDialog confirmDialog;

    private void showCreditConfirm(String txt) {
        if (confirmDialog == null) {
            confirmDialog = new TipDialog(getActivity());
        }
        confirmDialog.setContent(txt);
        confirmDialog.setCancelable(true);
        confirmDialog.setConfirm("去绑定");
        confirmDialog.show();
        confirmDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmDialog.dismiss();
                startActivity(AddCreditActivity.class);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmDialog.dismiss();
            }
        });
    }

//    private ConfirmDialog mConfirmDialog;
//
//    private void showConfirmDialog(String content) {
//        if (mConfirmDialog == null) {
//            mConfirmDialog = new ConfirmDialog(getActivity());
//        }
//        mConfirmDialog.setCancelable(true);
//        mConfirmDialog.setContent(content);
//        mConfirmDialog.show();
//        mConfirmDialog.setListener(new ConfirmDialog.Listener() {
//            @Override
//            public void onConfirm() {
//                super.onConfirm();
//                mConfirmDialog.cancel();
//            }
//        });
//    }


    private TipDialog mTipdialog;

    private void showTipDialog() {
        if (mTipdialog == null) {
            mTipdialog = new TipDialog(getActivity());
        }
        mTipdialog.setCancelable(false);
        mTipdialog.setContent("请先进行实名认证");
        mTipdialog.setConfirm("去认证");
        mTipdialog.show();
        mTipdialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                mTipdialog.cancel();
                startActivity(IdentifyActivity.class);//实名认证
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                mTipdialog.cancel();
            }
        });
    }

    private TipDialog mCarddialog;

    private void showCardDialog() {
        if (mCarddialog == null) {
            mCarddialog = new TipDialog(getActivity());
        }
        mCarddialog.setCancelable(false);
        mCarddialog.setContent("您尚未绑定银行卡,是否绑定？");
        mCarddialog.show();
        mCarddialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                startActivity(AddCardActivity.class);
                mCarddialog.dismiss();
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                mCarddialog.dismiss();
            }
        });
    }

    private TipDialog mCreditdialog;

    private void showCreditDialog() {
        if (mCreditdialog == null) {
            mCreditdialog = new TipDialog(getActivity());
        }
        mCreditdialog.setCancelable(false);
        mCreditdialog.setContent("您尚未绑定信用卡,是否绑定？");
        mCreditdialog.show();
        mCreditdialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                startActivity(AddCreditActivity.class);
                mCreditdialog.dismiss();
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                mCreditdialog.dismiss();
            }
        });
    }

    //账户信息
    private void getUserDetail() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.get_detail);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getActivity())) {
                    showToastShort(getString(R.string.net_state));
                }
                smartRefreshLayout.finishRefresh();
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                smartRefreshLayout.finishRefresh();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        UserDetailData data = GsonUtil.GsonToBean(string, UserDetailData.class);
                        App.getApp().setUserDetailInfo(data);//保存账户信息
                        Message message = Message.obtain();
                        message.obj = data;
                        message.what = TYPE_USER_DETAIL;
                        mHandler.sendMessage(message);
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private static int TYPE_USER_DETAIL = 0; //账户信息

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    UserDetailData data = (UserDetailData) msg.obj;
                    String mobile = data.getData().getUsername();
                    mTextMobile.setText(mobile);
                    int authType = data.getData().getReal_auth_status();
                    if (authType == 0) {
                        mTextRealName.setText("未认证");
                    } else if (authType == 1) {
                        mTextRealName.setText("审核中");
                    } else if (authType == 2) {
                        mTextRealName.setText("已认证");
                    }
                    int grade = data.getData().getGrade();
                    if (grade == 1) {
                        mTextHuiyuan.setText("普通会员");
                    } else if (grade == 2) {
                        mTextHuiyuan.setText("经纪商会员");
                    }
                    break;
            }

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(getThis());
    }

    private void getCreditData() {
        showProgress("加载中");
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.creditCard);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 0) {
                    } else {
                        CreditListData data = GsonUtil.GsonToBean(string, CreditListData.class);
                        if (data.getData().size() != 0) {
                            hasCredit = true;
                        } else {
                            hasCredit = false;
                        }
                    }
                }
            }
        });
    }
}
